package com.yang.util;

import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class EncryptionUtil {

	/**
	 * 登录密码加密，rzm
	 * 
	 * @param str
	 * @return
	 */
//	public static String password(String str) {
//		String password = DigestUtils.md5DigestAsHex(str.getBytes());
//		password = DigestUtils.md5DigestAsHex(password.getBytes());
//		return password;
//	}

	/**
	 * 登录密码加密，段
	 * 
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String password(String str) throws Exception {
		return encryptDES(str, "hrms@123");
	}

	private static String encryptDES(String encryptString, String encryptKey) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		IvParameterSpec zeroIv = new IvParameterSpec(encryptKey.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		DESKeySpec desKeySpec = new DESKeySpec(encryptKey.getBytes("UTF-8"));
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

		cipher.init(Cipher.ENCRYPT_MODE, secretKey, zeroIv);

		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
		
//		return new BASE64Encoder().encode(encryptedData);
		return Base64.getEncoder().encodeToString(encryptedData);
	}

	/**
	 * 登录密码密文破解
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public  static String decryptPassword(String str) throws Exception {
		return decryptDES(str, "ips#2014");
	}
	
	private static String decryptDES(String decryptString, String decryptKey) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		IvParameterSpec zeroIv = new IvParameterSpec(decryptKey.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		DESKeySpec desKeySpec = new DESKeySpec(decryptKey.getBytes("UTF-8"));
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

		cipher.init(Cipher.DECRYPT_MODE, secretKey, zeroIv);

//		byte[] byteMi = new BASE64Decoder().decodeBuffer(decryptString);
		byte[] byteMi = Base64.getDecoder().decode(decryptString);

		byte decryptedData[] = cipher.doFinal(byteMi);
		return new String(decryptedData);
	}

	/**
	 * base64加密
	 * 
	 * @param str
	 * @return
	 */
	public static String base64Encode(String str) {
		Encoder encoder = Base64.getEncoder();
		String base64Str = encoder.encodeToString(str.getBytes());
		return base64Str;
	}

	/**
	 * base64解密
	 * 
	 * @param str
	 * @return
	 */
	public static String base64Decode(String str) {
		Decoder decoder = Base64.getDecoder();
		byte[] decode = decoder.decode(str);
		return new String(decode);
	}
	
	public static void main(String[] args) throws Exception {
		String decryptPassword = decryptPassword("UvM++76ZSNlabZIngojBKA==");
		System.out.println(decryptPassword);
	}

}
